/**
 * $Id$
 *
 * Unpublished Work Copyright 2013 Confirmit, Inc. All Rights Reserved.
 *
 * Last changed by $Author$
 * Last changed at $Date$
 */
package com.youtills.core.app.pcc;

import com.youtills.core.app.common.ISiteLayout;
import com.youtills.core.app.common.SiteLayout;
import com.youtills.core.crypto.CipherFactory;
import com.youtills.core.crypto.CipherType;
import com.youtills.core.crypto.ICipher;
import com.youtills.core.lang.StringUtil;
import com.youtills.core.web.HttpUtil;
import com.youtills.core.web.IRequestHandler;
import org.apache.commons.codec.binary.Base64;

import java.nio.charset.Charset;

/**
 * TODO
 *
 * @author Ravi Kumar Chiluveru (RaviC)
 * @since 12.2, (7/10/13 5:17 PM)
 */
public class PccEvRequestHandler extends SiteLayout implements IRequestHandler, ISiteLayout {

    private static final String USER_COOKIE = "pcc.ev.user.id";
    private static final int COOKIE_TIME = 60 * 60 * 24 * 300;
    private static final ICipher cipher = CipherFactory.getCipher(CipherType.AES, "pcc$ev@1");

    public PccEvRequestHandler() {
    }

    public String getMainPage() {
        return "/WEB-INF/jsp/pcc/pcc.jsp";
    }

    private EvUser evUser;

    private static int getDecryptedUserId(String uid){
        try {
             return StringUtil.getNumber(new String(cipher.decrypt(new String(fromHexString(uid), "UTF-8"))), -2).intValue();

        }catch (Exception e) {
            return -2;
        }
    }

    private int getUserId(){
        doAction();
        String uId = (getContextBean().getRequest().getParameter("u"));
        int userId = getDecryptedUserId(uId);

        if(userId < 0){
            uId = HttpUtil.getCookieValue(getContextBean().getRequest(), USER_COOKIE);
            userId = getDecryptedUserId(uId);
        }

        if(userId > 0){
            HttpUtil.setCookie(getContextBean().getResponse(), USER_COOKIE, uId, COOKIE_TIME);
        }

        return userId;
    }

    public EvUser getEvUser() {
        if(evUser == null) {
            int u = getUserId() - 1;
            if(u >= 0 && u < EvUser.evUsers.length){
                evUser = EvUser.evUsers[u];
            }
        }
        return evUser;
    }

    private static ParkingSpace[] station(String s){
        ParkingSpace[] station = null;

        if(!StringUtil.isEmpty(s)) {
            if ("6200".equals(s)) {
                station = ParkingSpace.S_6200;
            } else if ("6210".equals(s)) {
                station = ParkingSpace.S_6210;
            } else if ("6220".equals(s)) {
                station = ParkingSpace.S_6220;
            } else if ("6230".equals(s)) {
                station = ParkingSpace.S_6230;
            }
        }

        return station;

    }

    private ParkingSpace[] station;
    public ParkingSpace[] getStation() {
        if(station == null){
            String s = getContextBean().getRequest().getParameter("s");
            station = station(s);

            if(station == null && getSpace() != null){
                station = station(getSpace().getStationName());
            }
        }
        return station;
    }

    public ParkingSpace space;

    public ParkingSpace getSpace() {
        if(space == null){
            String p = getContextBean().getRequest().getParameter("p");
            if(!StringUtil.isEmpty(p)) {
                space = ParkingSpace.valueOf(p);
            }
        }
        return space;
    }

    private boolean actionCompleted;

    private void doAction(){
        if(!actionCompleted) {
            actionCompleted = true;
            String a = getContextBean().getRequest().getParameter("a");
            if (!StringUtil.isEmpty(a)) {
                Action action = Action.valueOf(a);
                ParkingSpace ps = getSpace();
                if(ps != null && action != null) {
                    ps.doAction(getEvUser(), action);
                }
            }

        }
    }

    public enum Action {
        ci,
        pi,
        po,
        co,
        cc
    }


    public static void main(String args[]) throws Exception{
        for(int i = 1; i < 101; i++) {
            System.out.println(i + " = " + toHexString(cipher.encrypt(String.valueOf(i)).getBytes("UTF-8")));
        }
    }

    public static String toHexString(byte[] fieldData) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < fieldData.length; i++) {
            int v = (fieldData[i] & 0xFF);
            if (v <= 0xF) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString();
    }

    public static byte[] fromHexString(String s) {
        int length = s.length() / 2;
        byte[] bytes = new byte[length];
        for (int i = 0; i < length; i++) {
            bytes[i] = (byte) ((Character.digit(s.charAt(i * 2), 16) << 4) | Character
                    .digit(s.charAt((i * 2) + 1), 16));
        }
        return bytes;
    }

}